import React, { memo, useCallback, useEffect, useRef, useState } from "react";
import { useDispatch, useSelector, shallowEqual } from "react-redux";
import { NavLink } from "react-router-dom";
import { Slider } from "antd";
import classnames from "classnames";
import "./index.scss";

import playActions from "store/action/play";

import {
  getSizeImage,
  formatMinuteSecond,
  getPlaySong,
} from "@/utils/format-utils";

import WYAppPlayList from "../app-play-panel";

export default memo(function HYAppPlayerBar(props) {
  // redux数据
  const dispatch = useDispatch();
  const { currentSong, sequence, playList, lyricList, lyricIdX } = useSelector(
    (state) => ({
      currentSong: state.getIn(["play", "currentSong"]),
      sequence: state.getIn(["play", "sequence"]),
      playList: state.getIn(["play", "playList"]),
      lyricList: state.getIn(["play", "lyricList"]),
      lyricIdX: state.getIn(["play", "lyricIdX"]),
    }),
    shallowEqual
  );
  useEffect(() => {
    dispatch(playActions.getSongDetail(167876));
  }, [dispatch]);
  // state和props-ref
  const audioRef = useRef();
  const [currentTime, setCurrentTime] = useState(0);
  const [progress, setProgress] = useState(0);
  const [isChange, setIsChang] = useState(false);
  const [isPlaying, setIsPlaying] = useState(false);
  const [showPanel, setShowPanel] = useState(false);
  //   其它逻辑
  const picUrl = (currentSong.al && currentSong.al.picUrl) || "";
  const singerName = (currentSong.ar && currentSong.ar[0].name) || "未知歌手";
  const duration = currentSong.dt || 0; //总时长

  useEffect(() => {
    // 每次切换歌曲 刷新数据
    setCurrentTime(0);
    setProgress(0);
    setIsChang(false);
    setIsPlaying(false);

    // 获取歌曲信息
    audioRef.current.src = getPlaySong(currentSong.id); //这里调用这个方法，拼接的链接。然后返回音频流媒体
    audioRef.current
      .play()
      .then((res) => {
        setIsPlaying(true);
      })
      .catch((err) => {
        setIsPlaying(false);
      });
  }, [currentSong]);

  // 其它处理函数
  // 播放
  const playMusic = useCallback(() => {
    isPlaying ? audioRef.current.pause() : audioRef.current.play();
    setIsPlaying(!isPlaying);
  }, [isPlaying]);

  const onTimeUpdate = (e) => {
    let currentTime = e.target.currentTime;
    if (!isChange) {
      //没有拉动滑块的时候设置显示时间和进度
      setCurrentTime(currentTime * 1000);
      setProgress(((currentTime * 1000) / duration) * 100);
    }
    if(parseInt(((currentTime * 1000) / duration) * 100)===100){
      setIsChang(false);
      setIsPlaying(false);
      // 一首歌曲播放完成就调用下一首
      changePlay(1)
    }

    // 获取歌词
    let i = 0;
    for (; i < lyricList.length; i++) {
      let lyricItem = lyricList[i];
      if (currentTime * 1000 < lyricItem.time) {
        break;
      }
    }
    if (i - 1 !== lyricIdX) {
      dispatch(playActions.setLyricIdx(i - 1));
      // const content = lyricList[i - 1] && lyricList[i - 1].content;
      // 显示歌词
      // message.open({
      //   key: "lyric",
      //   content: content,
      //   duration: 0,
      //   className: "lyric-class",
      // });
    }
  };

  const sliderChange = useCallback((value) => {
    setIsChang(true);
    setProgress(value);
  }, []);
  const sliderAfterChange = useCallback(
    (value) => {
      const currentTime = ((value / 100) * duration) / 1000;
      audioRef.current.currentTime = currentTime;
      setCurrentTime(currentTime * 1000);
      setIsChang(false);
      if (!isPlaying) {
        playMusic();
      }
    },
    [duration, isPlaying, playMusic]
  );
  const changeSequence = () => {
    if (sequence <= 1) {
      dispatch(playActions.changeSequence(sequence + 1));
    } else {
      dispatch(playActions.changeSequence(0));
    }
  };
  // 点击 -1上一首 +1下一首（如果单纯是播放完了 其实应该监听滚动条进度然后调用-那种需要吧这个方法进行拆分）
  const changePlay = (tag) => {
    // 先判断是不是单曲循环
    if (sequence === 2) {
      audioRef.current.currentTime = 0;
    } else {
      // 在调用切换上一首或者下一首方法
      dispatch(playActions.changePlay(tag));
    }
  };

  return (
    <div className="app-player-bar  sprite_player">
      <div className="player-content wrap-v2">
        {/* 播放控件 */}
        <div className="control">
          {/* 上一曲 */}
          <button
            className="sprite_player prev"
            onClick={(e) => changePlay(-1)}
          ></button>
          <button
            className={classnames(
              "sprite_player play",
              !isPlaying ? "play-end" : "play-begin"
            )}
            onClick={(e) => playMusic()}
          ></button>
          {/* 下一曲 */}
          <button
            className="sprite_player next"
            onClick={(e) => changePlay(1)}
          ></button>
        </div>
        {/* 进度条  */}
        <div className="play-info">
          <div className="image">
            <NavLink to="/discover/player">
              <img src={getSizeImage(picUrl, 35)} alt="" />
            </NavLink>
          </div>
          <div className="info">
            <div className="song">
              <span className="song-name">{currentSong.name}</span>
              <a href="#/" className="singer-name">
                {singerName}
              </a>
            </div>
            {/* 进度条 */}
            <div className="progress">
              <Slider
                defaultValue={30}
                value={progress}
                onChange={sliderChange}
                onAfterChange={sliderAfterChange}
              />
              <div className="time">
                <span className="now-time">
                  {formatMinuteSecond(currentTime)}
                </span>
                <span className="divider">/</span>
                <span className="duration">{formatMinuteSecond(duration)}</span>
              </div>
            </div>
          </div>
        </div>
        {/* 最右边  */}
        <div className="operator">
          <div className="left">
            <button className="sprite_player btn favor"></button>
            <button className="sprite_player btn share"></button>
          </div>
          <div className="right sprite_player">
            <button className="sprite_player btn volume"></button>
            <button
              className={classnames("sprite_player btn", `loop${sequence}`)}
              onClick={(e) => changeSequence()}
            ></button>
            <button className="sprite_player btn playlist" onClick={e=>setShowPanel(!showPanel)}></button>
            <div className="num">{playList.length}</div>
          </div>
        </div>
      </div>
      <audio ref={audioRef} onTimeUpdate={onTimeUpdate} />
              { showPanel && <WYAppPlayList/>}
    </div>
  );
});
